package cn.cellcom.agent.online.iq.visitor;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.biz.TSessionBiz;
import cn.cellcom.agent.biz.TSettingBiz;
import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.entity.TSettingEntity;
import cn.cellcom.agent.online.client.Client;
import cn.cellcom.agent.online.client.SessionManager;
import cn.cellcom.agent.online.client.VisitorClient;
import cn.cellcom.agent.online.iq.AbstractChainedProcessor;
import cn.cellcom.agent.online.iq.Processor;
import cn.cellcom.agent.online.iq.ProcessorResult;
import cn.cellcom.agent.online.message.MessageConstant;
import cn.cellcom.agent.online.wrapper.SessionWrapper;
import cn.cellcom.agent.pojo.TSession;
import cn.cellcom.agent.struts.form.VisitorForm;
import cn.cellcom.agent.util.ThirdCallbackUtils;
import cn.cellcom.agent.util.ThreadPool;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.util.MyException;

public class SatisfyProcessor extends AbstractChainedProcessor {

	public static final String NAME = MessageConstant.MESSAGE_EVENT.DO_SATISFY.name();

	private Logger log = LoggerFactory.getLogger(this.getClass());

	public SatisfyProcessor(Processor next) {
		super(next);
	}

	@Override
	public ProcessorResult doProcess(Map<String, AbstractBiz> bizs, Client client, VisitorForm cf) {
		final VisitorClient vc = (VisitorClient) client;
		TSession tsession = null;
		final SessionWrapper session = SessionManager.getInstance().getPool(cf.getPid()).getSession(cf.getSid());
		if (session != null) {// 如果内存中还有数据
			tsession = session.getSession();
		} else {// 如果会话结束后才进行评价，那么需要修改数据库
			try {
				TSessionBiz ssbiz = (TSessionBiz) bizs.get("ssbiz");
				tsession = (TSession) ssbiz.getDao().myGet(TSession.class, cf.getSid());
			} catch (MyException e) {
				log.error("[{}] get session by sid[{}] fail", client.getId(), cf.getSid(), e.getException());
			}
		}
		if (StringUtils.isNotBlank(cf.getValue2()) && cf.getValue2().length() > 300) {
			log.info("[{}] do satisfy[{}] for the session[{}] but input to long", vc.getId(), cf.getValue2().length(), cf.getSid());
			return new ProcessorResult(false, this, null);
		}
		if (tsession != null) {
			tsession.setSatisfyScore(Short.parseShort(cf.getValue()));
			tsession.setSatisfyText(cf.getValue2());
			vc.updateSessionDb(tsession);
			if (session != null) {
				vc.sendSession(tsession);
			}
		} else {
			log.error("[{}] do satisfy by sid[{}], but the tsession is null", vc.getId(), cf.getSid());
		}
		// 以下为了实现满意度评价通知
		TSettingEntity setting = null;
		if (session != null) {// 对于结束的会话进行评价，需要查询配置
			setting = session.getSetting();
		} else {
			TSettingBiz sbiz = (TSettingBiz) bizs.get("sbiz");
			try {
				setting = sbiz.getOrgSetting(tsession.getOrg(), tsession.getPid());
			} catch (MyException e) {
				log.error("get setting fail.", e.getException());
			}
		}
		if (StringUtils.isNotBlank(setting.getCallUrl()) && setting.getCallMethod().contains(AgentConstant.ThirdCallback.satisfy.name())) {
			final Map<String, Object> map = new HashMap<String, Object>();
			final TSettingEntity setting2 = setting;
			map.put("sessionId", tsession.getId());
			map.put("score", cf.getValue());
			map.put("text", cf.getValue2());
			ThreadPool.Execute(new Runnable() {
				@Override
				public void run() {
					ThirdCallbackUtils.call(AgentConstant.ThirdCallback.satisfy, vc.getCrm().getTid(), setting2.getAccessKey(), setting2.getCallUrl(),
							map, null);
				}
			});
		}
		log.info("[{}] do satisfy[{}] for the session[{}]", vc.getId(), cf.getValue(), cf.getSid());
		return new ProcessorResult(true, this, null);
	}

	@Override
	public boolean isAcceptable(VisitorForm message) {
		return NAME.equals(message.getEvent());
	}
}
